// https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/

// 算法思路总结：
// 1. 递归分治从前序与中序遍历序列构造二叉树
// 2. 前序序列首元素为根节点，在中序序列中定位根节点位置
// 3. 根据根节点位置划分左右子树区间递归构建
// 4. 使用引用参数跟踪前序序列当前处理位置
// 5. 时间复杂度：O(n)，空间复杂度：O(h)

#include <iostream>
using namespace std;

#include <stack>
#include <vector>
#include <algorithm>
#include "BinaryTreeUtils.h"

class Solution 
{
public:
    TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder, int& prei, int inbegin, int inend)
    {
        if (inbegin > inend)
        {
            return nullptr;
        }

        TreeNode* root = new TreeNode(preorder[prei++]);
        int rooti = inbegin;
        while (inorder[rooti] != root->val)
        {
            rooti++;
        }

        root->left = _buildTree(preorder, inorder, prei, inbegin, rooti - 1);
        root->right = _buildTree(preorder, inorder, prei, rooti + 1, inend);

        return root;
    }

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) 
    {
        int i = 0;
        return _buildTree(preorder, inorder, i, 0, inorder.size() - 1);
    }
};

int main()
{
    vector<int> preorder1 = {3,9,20,15,7}, inorder1 = {9,3,15,20,7};
    vector<int> preorder2 = {-1}, inorder2 = {-1};

    Solution sol;

    cout << (sol.buildTree(preorder1, inorder1)->val) << endl;
    cout << (sol.buildTree(preorder2, inorder2)->val) << endl;

    return 0;
}